package com.gujiangbo.juc;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * @Author: gujiangbo.co
 * @Contact: 646832012@qq.com
 * @Date: 2022/6/5 08:19
 * @Version: 1.0
 * @Description:
 */
public class CompleteFutureUseTest {

    public static void main(String[] args) {
       // applyToEither();
        thenCombine();
    }

    private static void thenCombine() {
        CompletableFuture<List<String>> a = CompletableFuture.supplyAsync(() -> {
            System.out.println("A is run..");
            List<String> list = new ArrayList<>();
            IntStream.range(0, 10).forEach(v -> list.add(UUID.randomUUID().toString().substring(0,5)));
            return list;
        });

        CompletableFuture<List<String>> b = CompletableFuture.supplyAsync(() -> {
            System.out.println("B is run..");
            List<String> list = new ArrayList<>();
            IntStream.range(0, 5).forEach(v -> list.add("b" + v));
            return list;
        });

        CompletableFuture<List<String>> result = a.thenCombine(b, (i, j) -> {
            System.out.println("开始运算...");
            i.addAll(j);
            return i;
        });

        System.out.println(result.join());
    }

    private static void applyToEither() {
        CompletableFuture<String> playA = CompletableFuture.supplyAsync(() -> {
            System.out.println("A is come in..");
            //暂停5秒钟线程
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "play A";
        });


        CompletableFuture<String> playB = CompletableFuture.supplyAsync(() -> {
            System.out.println("B is come in..");
            //暂停5秒钟线程
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "play B";
        });

        CompletableFuture<String> result = playA.applyToEither(playB, f -> f + " is winner");

        System.out.println(result.join());
    }
}
